//单链表的节点
function LinkedNode(key) {
    this.key = key;
    this.next = null;
    this.pre = null;
}

//单链表
function LinkedList() {

    // 头节点
    let head = null;

    //插入
    this.insert = function (key) {
        let node = new LinkedNode(key);
        if (head === null) {
            head = node;
            return;
        }
        let p = head;
        while (p.next != null) {
            p = p.next;
        }
        p.next = node;

    }

    //删除 指定位置的值
    this.delete = function (position = 0) {
        if (position === 0) {
            console.log(head.key + "被删除");
            head = head.next;
        } else if (position < 0) {
            console.log("此位置不合法");
        }
        else {
            let i = 0;
            let p = head;
            let pre;
            while (p) {
                if (i === position) {
                    pre.head = p.next;
                    console.log(p.key + "被删除");
                    return;
                }
                i++;
                pre = p;
                p = p.next;
            }
            console.log("此位置不存在");
        }
    }

    //遍历
    this.print = function () {
        let p = head;
        let str = "";
        while (p) {
            str += (p.key + " ");
            p = p.next;
        }
        console.log(str);
    }

    //长度
    this.getLength = function () {
        let len = 0;
        let p = head;
        while (p) {
            len++;
            p = p.next;
        }
        return len;
    }

}

// node linkedlist/linled_list.js
const nodes = [66, 34, 98, 12, 88];
let list = new LinkedList();
let len = nodes.length;
for (let i = 0; i < len; i++) {
    list.insert(nodes[i], null);
}
list.print();
list.delete(3);
list.delete();
list.print();
console.log("长度：" + list.getLength());

